package per.turtle.common.core.annotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.nio.charset.Charset;

/**
 * @author turtle
 */
public class MaxSizeWithCharsetValidator implements ConstraintValidator<MaxSizeWithCharset, String> {

    private int max;

    private String charset;

    @Override
    public void initialize(MaxSizeWithCharset constraintAnnotation) {
        this.max = constraintAnnotation.max();
        this.charset = constraintAnnotation.charset();
    }

    @Override
    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
        return object == null || object.getBytes(Charset.forName(this.charset)).length <= this.max;
    }

}

